<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数量" prop="productSalesQuantity">
        <el-input
          v-model="queryParams.productSalesQuantity"
          placeholder="请输入数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['storage:salesDetail:edit']"
        >订单出库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['storage:salesDetail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="salesDetailList" @selection-change="handleSelectionChange" :span-method="objectSpanMethod">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderId" />
      <el-table-column label="商品名" align="center" prop="productId" />
      <el-table-column label="数量" align="center" prop="productSalesQuantity" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
    <span v-if="scope.$index === 0 || scope.row.orderId !== salesDetailList[scope.$index - 1].orderId">
      <el-button
        size="mini"
        type="text"
        icon="el-icon-edit"
        @click="handleUpdate(scope.row)"
        v-hasPermi="['storage:salesDetail:edit']"
      >订单出库</el-button>
      <el-button
        size="mini"
        type="text"
        icon="el-icon-delete"
        @click="handleDelete(scope.row)"
        v-hasPermi="['storage:salesDetail:remove']"
      >删除</el-button>
    </span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--   添加可增加行的多行输入框     -->
        <template >
          <el-divider content-position="center">逐件输入出库商品编码</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddProduct">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" >扫码录入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteProduct">删除</el-button>
            </el-col>
          </el-row>
          <el-table :data="productList" @selection-change="handleProductSelectionChange" ref="productTable">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="序号" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="商品编码" prop="code" width="150">
              <template slot-scope="scope">
                <el-input v-model="productList[scope.$index]" placeholder="请输入商品编码" />
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSalesDetail,
  getSalesDetail,
  delSalesDetail,
  addSalesDetail,
  updateSalesDetail,
  salesExit
} from "@/api/storage/salesDetail";
import {addProcessRecord, updateProcessRecord} from "@/api/storage/processRecord";

export default {
  name: "SalesDetail",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单出库表格数据
      salesDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        productId: null,
        pageNum: 1,
        pageSize: 10,
        warehouseCode: null,
        subtotal: null,
        productSalesQuantity: null,
        discount: null,
        totalAmount: null,
        addressId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      productList: [],
      checkedProducts: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单出库列表 */
    getList() {
      this.loading = true;
      this.queryParams.status = "4";
      listSalesDetail(this.queryParams).then(response => {

        this.salesDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        productId: null,
        warehouseCode: null,
        subtotal: null,
        productSalesQuantity: null,
        discount: null,
        totalAmount: null,
        addressId: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单出库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "订单出库";
      this.form.orderId = row.orderId || this.ids

    },
    /** 提交按钮 */
    submitForm() {
      this.form.productList = this.productList;
      if (this.form.orderId != null){
        salesExit(this.form).then(response => {
          this.$modal.msgSuccess("出库成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单出库编号为"' + orderIds + '"的数据项？').then(function() {
        return delSalesDetail(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('storage/salesDetail/export', {
        ...this.queryParams
      }, `salesDetail_${new Date().getTime()}.xlsx`)
    },

    /** 订单编号合并 */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) { // 假设订单编号在第二列
        if (rowIndex === 0) {
          return {
            rowspan: this.getSpanCount(rowIndex, 'orderId'),
            colspan: 1
          };
        } else {
          if (row.orderId === this.salesDetailList[rowIndex - 1].orderId) {
            return {
              rowspan: 0,
              colspan: 0
            };
          } else {
            return {
              rowspan: this.getSpanCount(rowIndex, 'orderId'),
              colspan: 1
            };
          }
        }
      }
    },
    getSpanCount(index, field) {
      let count = 1;
      for (let i = index + 1; i < this.salesDetailList.length; i++) {
        if (this.salesDetailList[i][field] === this.salesDetailList[index][field]) {
          count++;
        } else {
          break;
        }
      }
      return count;
    },

    // 多行输入商品编码
    /** 商品编码添加按钮操作 */
    handleAddProduct() {
      this.productList.push("");
    },
    /** 商品编码删除按钮操作 */
    handleDeleteProduct() {
      if (this.checkedProducts.length == 0) {
        this.$modal.msgError("请先选择要删除的商品编码");
      } else {
        this.productList = this.productList.filter((_, index) => !this.checkedProducts.includes(index));
        this.checkedProducts = [];
      }
    },
    /** 复选框选中数据 */
    handleProductSelectionChange(selection) {
      this.checkedProducts = selection.map(item => this.productList.indexOf(item));

    },

  }
};
</script>
